package cn.cyber.wxfire.service;

import cn.cyber.wxfire.config.WXConfig;
import cn.cyber.wxfire.dto.AccessTokenDto;
import cn.cyber.wxfire.entity.AccessToken;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author gjn
 * @since 2021/9/18 9:35
 */
@Service
public class AccessTokenService {
    @Resource
    private WXService wxService;
    @Resource
    private WXConfig config;
    private AccessTokenDto tokenDto;


    public String getAccessTokenStr() {
        if ( (this.tokenDto == null) || (System.currentTimeMillis() > this.tokenDto.getExpireTime()) ) {
            this.getAccessTokenDto();
        }
        return this.tokenDto.getAccessToken();
    }

    public void getAccessTokenDto() {
        AccessToken token = wxService.getAccessTokenStrFromServer("client_credential", config.getAppID(), config.getAppSecret());
        this.tokenDto = new AccessTokenDto(token.getAccess_token(),
                                 System.currentTimeMillis() + 7200*1000);
    }

    public boolean isExpired(AccessTokenDto tokenDto) {
        return System.currentTimeMillis() > tokenDto.getExpireTime();
    }
}
